#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int main()
{
    FILE *fd = NULL;
    long string=0;
    char buff[] = "正点原子http://www.openedv.com/forum.php";

    fd = fopen("./test.txt","w+");
    if(fd == NULL){
        perror("创建/打开文件失败");
        fclose(fd);
        exit(-1);
    }
    printf("创建/打开文件成功!\n");

    size_t num;
    //打开/创建文件后写入数据
    num = fwrite(buff,1,sizeof(buff),fd);
    if(num < sizeof(buff)){
        if(ferror(fd)){
            printf("写入错误\n");
            fclose(fd);
            exit(-1);
        }
    }
    printf("写入成功，写入数据项为: %ld\n",num);

    //将读写位置移动到文件末尾 
    if (0 > fseek(fd, 0, SEEK_END)) { 
        perror("设置文件偏移量失败：SEEK_END"); 
        fclose(fd); 
        exit(-1); 
    } 

    //获取当前位置偏移量
    if(0 > (string=ftell(fd))){
        perror("获取写操作后的文件偏移量失败");
        fclose(fd);
        exit(-1);
    }

    if(0 > fseek(fd,19,SEEK_SET)){
        perror("设置文件偏移量失败：SEEK_SET");
        fclose(fd);
        exit(-1);
    }
    
    char rd_buff[50] = {'\0'};
    num = fread(rd_buff,1,sizeof(buff),fd);
    if(num < sizeof(buff)){
        if(ferror(fd)){
            printf("读取错误\n");
            fclose(fd);
            exit(-1);
        }
        if(feof(fd)){
            printf("到达文件末尾，读取结束\n");
            // fclose(fd);
            // exit(-1);
        }
    }
    printf("读取成功,buff长度为:%ld  buff为:%s\n",strlen(rd_buff),rd_buff);

    printf("test.txt 文件大小为：%ld\n",string);

    if(0 > fclose(fd)){
        perror("关闭文件失败");
        exit(-1);
    }

    return 0;
}